import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rembercount/controller/countController.dart';
import 'package:rembercount/controller/themeController.dart';

class Myaccount extends StatefulWidget {
  const Myaccount({super.key});

  @override
  State<Myaccount> createState() => _MyaccountState();
}

class _MyaccountState extends State<Myaccount> {
  CountController countController = Get.find<CountController>();
  ThemeController themeController=Get.find<ThemeController>();
  List<Map<String, dynamic>> assetTypes = [];
  int selectedType = 0;
  List<String> iconKeys = iconMap.keys.toList();
  int selectedIconIndex = 0;
  final TextEditingController nameController = TextEditingController();

  // icon字符串到IconData的映射
  static const Map<String, IconData> iconMap = {
    'wallet': Icons.account_balance_wallet,
    'bank': Icons.account_balance,
    'alipay': Icons.payment,
    'wechat': Icons.wechat,
    'credit_card': Icons.credit_card,
    'saving': Icons.savings,
    // 可根据后端返回补充更多
  };

  @override
  void initState() {
    super.initState();
    getAssetType();
  }

  Future<void> getAssetType() async {
    var res = await countController.getAssetType();
    print("_MyaccountState: $res");
    setState(() {
      assetTypes = List<Map<String, dynamic>>.from(res);
      countController.assetTypes = assetTypes;
    });
  }

  IconData getIcon(dynamic icon) {
    if (icon is IconData) return icon;
    if (icon is String && iconMap.containsKey(icon)) return iconMap[icon]!;
    return Icons.account_balance_wallet;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加资产类型'),
        centerTitle: true,
        backgroundColor:  themeController.themeColor,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '选择图标',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 12),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    ...List.generate(iconKeys.length, (index) {
                      String key = iconKeys[index];
                      return GestureDetector(
                        onTap: () {
                          setState(() {
                            selectedIconIndex = index;
                          });
                        },
                        child: Container(
                          margin: const EdgeInsets.only(right: 8),
                          padding: const EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color:
                                selectedIconIndex == index
                                    ? themeController.themeColor.withOpacity(0.1)
                                    : Colors.grey[100],
                            border: Border.all(
                              color:
                                  selectedIconIndex == index
                                      ? themeController.themeColor
                                      : Colors.transparent,
                              width: 2,
                            ),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Icon(
                            iconMap[key],
                            color:
                                selectedIconIndex == index
                                    ?  themeController.themeColor
                                    : Colors.grey,
                            size: 32,
                          ),
                        ),
                      );
                    }),
                  ],
                ),
              ),
              if (countController.assetTypes.isNotEmpty) ...[
                const SizedBox(height: 16),
                const Text(
                  '已有资产类型',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: countController.assetTypes.map<Widget>((item) {
                      return Container(
                        margin: const EdgeInsets.only(right: 8),
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color:  themeController.themeColor, width: 1),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              getIcon(item['icon']),
                              color:  themeController.themeColor,
                              size: 20,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              item['label'] ?? '',
                              style: const TextStyle(fontSize: 13),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ],
              const SizedBox(height: 32),
              TextField(
                controller: nameController,
                decoration: InputDecoration(
                  labelText: '资产类型名称',
                  border: const OutlineInputBorder(),
                  prefixIcon: Icon(
                    iconMap[iconKeys[selectedIconIndex]],
                    color:  themeController.themeColor,
                  ),
                ),
              ),
              const SizedBox(height: 40),
              SizedBox(
                width: double.infinity,
                height: 48,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor:  themeController.themeColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  onPressed: () async {
                    String name = nameController.text.trim();
                    if (name.isEmpty) {
                      Get.snackbar('提示', '请输入资产类型名称');
                      return;
                    }
                    for (var element in countController.assetTypes) {
                      // print("element: ${element['label']}==$name");
                      if (element['label'] == name) {
                        Get.snackbar(
                          '提示',
                          '资产类型已存在',
                          backgroundColor: const Color.fromARGB(128, 244, 67, 54),
                          colorText: Colors.white,
                        );
                        return;
                      }
                    }
                    setState(() {
                      countController.assetTypes.add({
                        'icon': iconKeys[selectedIconIndex],
                        'label': name,
                      });
                      assetTypes = List<Map<String, dynamic>>.from(
                        countController.assetTypes,
                      );
                    });
                    var res = await countController.saveAssetType();
                    print("saveAssetType: $res");
                    Get.snackbar('成功', '资产类型添加成功');
                    // Navigator.pop(context);
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
